package com.thinkgem.jeesite.modules.dispatch.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.base.Strings;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.KDniao.entity.LogisticsCode;
import com.thinkgem.jeesite.modules.KDniao.entity.requestKDniao.responseKDniaoResult;
import com.thinkgem.jeesite.modules.KDniao.service.logistics.LogisticsCodeService;
import com.thinkgem.jeesite.modules.KDniao.service.meRequest.KdniaoSubscribeAPI;
import com.thinkgem.jeesite.modules.dispatch.entity.ShopDispatch;
import com.thinkgem.jeesite.modules.dispatch.service.ShopDispatchService;
import com.thinkgem.jeesite.modules.shop.constant.order.ShopOrderConstant;
import com.thinkgem.jeesite.modules.shop.entity.order.ShopOrder;
import com.thinkgem.jeesite.modules.shop.service.order.ShopOrderService;
import com.thinkgem.jeesite.modules.shop.service.receiving.ShopOrderReceivingService;

/**
 * 发货单Controller
 * 
 * @author ws
 * @version 2016-12-23
 */
@Controller
@RequestMapping(value = "${adminPath}/shop/dispatch")
public class ShopDispatchController extends BaseController {

    @Autowired
    ShopDispatchService shopDispatchService;
    
    @Autowired
    private ShopOrderService  shopOrderService;
    
    @Autowired
    private ShopOrderReceivingService shopOrderReceivingService;

    @Autowired
    private LogisticsCodeService logisticsCodeService;

    @Autowired
    private KdniaoSubscribeAPI kdniaoSubscribeAPI;
    @ModelAttribute
    public ShopDispatch get(@RequestParam(required = false) String id) {
        ShopDispatch entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = shopDispatchService.get(id);
        }
        if (entity == null) {
            entity = new ShopDispatch();
        }
        return entity;
    }

    @RequiresPermissions("shop:dispatch:manage:view")
    @RequestMapping(value = { "list", "" })
    public String list(ShopDispatch shopDispatch, HttpServletRequest request,
            HttpServletResponse response, Model model) {
        Page<ShopDispatch> page = shopDispatchService
                .findPage(new Page<ShopDispatch>(request, response),
                        shopDispatch);
        getlogisticsCodes(model);
        model.addAttribute("page", page);
        return "modules/shop/dispatch/shopDispatchList";
    }

    @RequiresPermissions("shop:dispatch:manage:view")
    @RequestMapping(value = "form")
    public String form(String id, Model model) {
        ShopDispatch shopDispatch = shopDispatchService.getById(id);
        getlogisticsCodes(model);
        model.addAttribute("shopDispatch", shopDispatch);
        return "modules/shop/dispatch/shopDispatchForm";
    }

    @RequiresPermissions("shop:dispatch:manage:edit")
    @RequestMapping(value = "save")
    @Transactional
    public String save(ShopDispatch shopDispatch, Model model,
            RedirectAttributes redirectAttributes) throws Exception {
        shopDispatchService.save(shopDispatch);
        if(shopDispatch.getStatus()==ShopOrderConstant.DISPATCHORDER_CONFIRMED){
    		//发货单填写快递单号 等信息  发货单进行发货   同时更新订单状态   
    		ShopOrder shopOrder=shopOrderService.get(shopDispatch.getOrderId());
    		shopOrder.setStatus(ShopOrderConstant.ORDER_PRODUCT_INPUT);
    		if(!Strings.isNullOrEmpty(shopDispatch.getCode())){
    			shopOrder.getShopOrderReceiving().setCode(shopDispatch.getCode());
    		}
    		if(!Strings.isNullOrEmpty(shopDispatch.getCompany())){
    			shopOrder.getShopOrderReceiving().setCompany(shopDispatch.getCompany());
    		}
    		shopOrderReceivingService.save(shopOrder.getShopOrderReceiving());
    		shopOrderService.save(shopOrder);
            //判断物流公司是否为空是则抛出错误。
            if (shopDispatch.getCompany() == null || "".equals(shopDispatch.getCompany()) || shopDispatch.getCode() == null
                    || "".equals(shopDispatch.getCode())) {
                addMessage(redirectAttributes, "物流公司和物流单号不能为空。");
                logger.error("物流公司和物流单号不能为空");
                throw new Exception("物流公司和物流单号不能为空");
            }
            responseKDniaoResult responseKDniaoResult = kdniaoSubscribeAPI
                    .orderTracesSubByJson(shopDispatch.getCompany(), shopDispatch.getOrderId(), shopDispatch.getCode());
            //排除是否重复订阅
            if (responseKDniaoResult != null) {
                if (!responseKDniaoResult.isSuccess()) {
                    addMessage(redirectAttributes, "订阅物流轨迹失败。失败原因：" + responseKDniaoResult.getReason());
                    logger.error("订阅物流轨迹失败。失败原因：" + responseKDniaoResult.getReason());
                    throw new Exception("订阅物流轨迹失败" + responseKDniaoResult.getReason());
                }
                logger.info(shopDispatch.getCompany() + "=====" + shopDispatch.getOrderId() + "======订阅物流轨迹成功");
            }
        }
    	if(shopDispatch.getStatus()==ShopOrderConstant.DISPATCHORDER_FINISHED){
    		//发货单进行收货确认   同时更新订单状态
    		ShopOrder shopOrder=shopOrderService.get(shopDispatch.getOrderId());
    		shopOrder.setStatus(ShopOrderConstant.ORDER_COMMIT);
    		shopOrderService.save(shopOrder);
    	}
        addMessage(redirectAttributes, "保存购物订单成功");
        return "redirect:" + Global.getAdminPath()
                + "/shop/dispatch/?repage";
    }

    @RequiresPermissions("shop:dispatch:manage:delete")
    @RequestMapping(value = "delete")
    public String delete(ShopDispatch shopDispatch,
            RedirectAttributes redirectAttributes) {
        shopDispatchService.delete(shopDispatch);
        addMessage(redirectAttributes, "删除购物订单成功");
        return "redirect:" + Global.getAdminPath()
                + "/shop/dispatch/?repage";
    }

    @RequiresPermissions("shop:dispatch:manage:view")
    @RequestMapping(value = "print")
    public String getById(String id, Model model) {
        ShopDispatch shopDispatch = shopDispatchService.getById(id);
        model.addAttribute("shopDispatch", shopDispatch);
        return "modules/shop/dispatch/shopDispatchPrint";
    }

    @SuppressWarnings("unchecked")
    public void getlogisticsCodes(Model model) {
        List<LogisticsCode> logisticsCodes = (List<LogisticsCode>) CacheUtils.get("logisticsCodesisenadleList");
        logger.info("物流公司信息===" + logisticsCodes);
        if (logisticsCodes == null || logisticsCodes.size() == 0) {
            logisticsCodes = logisticsCodeService.findisenadleList();
            CacheUtils.put("logisticsCodesisenadleList", logisticsCodes);
            logger.info("物流公司信息===" + logisticsCodes.toString());
        }
        model.addAttribute("logisticsCodes", logisticsCodes);
    }
}
